package _a;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import com.wili.c.Class9;
import com.wili.c.Misc9;
import com.wili.c.asm.Coms2b;
import com.wili.c.asm.FindPutFieldFromClassFile;
import com.wili.insertLog.InfunMap;
import com.wili.insertLog.InfunMap.Infun;
/**
 * 
 * @author weila 2021年3月7日
 */
public class Logu {
	/**
	 * 	向前深入一步拦截相关属性。例如：att1=fun(obj.att2), 工具不仅拦截att1还将拦截att2.
	 */
	public static final boolean logRelatedField = "asdf".isEmpty();

	public static final File ConfRoot = new File("c:/t/insertLog");

	static int taskOpt = 2;
	/**
	 * ... find java file from these root dirs(源代码的根目录).
	 */
	public static File[] getRootDirs_ofSourceFile() {
		if (taskOpt == 1)
			return new File[] { new File("D:\\bearJ\\autoeq2\\src\\main\\src_core") };
		if (taskOpt == 2) {
			File root = new File("D:/bearJ/autoeq2/src/main");
			return root.listFiles(new FileFilter() {
				@Override
				public boolean accept(File pathname) {
					return pathname.isDirectory() && pathname.getName().startsWith("src");
				}
			});
		}
		return null;
	}

	/**
	 * .此选项表明，只关心指定包下的文件。
	 */
	public static final Boolean isAcceptPackage(Class<?> cls) {
		if (taskOpt == 1)
			return _pkgSet.contains(cls.getPackageName());
		if (taskOpt == 2)
			return true;
		return null;
	}
	static Set<String> _pkgSet = new HashSet<>(Arrays.asList("wili.c.asm"));
	/**
	 * 
	 * @param opt
	 * @param logId
	 * @param name
	 * @param value
	 */
	public static void log(int opt, int logId, String name, Object value) {
		if (opt < 0)
			return;
		Infun funInfo = InfunMap.getInfun(logId);
		if (++inc == 23)
			pause();
		String st = funInfo.linkStr;
		st += "\n\tLogu" + inc + ", " + name + "=" + value;
		System.out.println(st);
	}

	static void pause() {
	}

	public static void main(String[] args) {
		FindPutFieldFromClassFile.SourceRootDirs = Logu.getRootDirs_ofSourceFile();
		//
		System.out.println("Usage: $className $fieldName | r: removeLog");
		String msg = Misc9.readCmdLine(">>> InsertLog to field:");
		Class<?> clazz;
		String fieldName;
		if (msg.matches("r|0")) {
			//从源码文件中删除自动插入的日志
			Coms2b.removeLog_fromDirs();
		} else {
			if (msg.isEmpty()) {
				clazz = null;// wili.insertLog.Cexp.class;
				fieldName = "value";
			} else {
				String[] mm = msg.split("\\s+");
				clazz = Class9.forName(mm[0], -1);
				fieldName = mm[1].trim();
			}
			//扫描所有给定属性的赋值语句，自动插入日志（使运行时能输出属性值）
			FindPutFieldFromClassFile.findField_then_insertLog(1, clazz, fieldName);
		}
		System.out.println("end.");
	}
	static int inc;
}
